package com.orange.base.component.biztool.simulateddata.service.impl;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;

import com.orange.base.component.biztool.simulateddata.util.JsonUtil;

public abstract class AbstractJson extends AbstractSimulatedData {

    public static final Map<String, Object> CACHE = new HashMap<String, Object>();

    public Object getData(Map<String, Object> param, String type) {
        try {
            String fileName = getFileName();
            Object datas = null;
            if (CACHE.containsKey(fileName)) {
                datas = CACHE.get(fileName);
            } else {
                // 获取文件的真实路径
                InputStream is = AbstractJson.class.getClassLoader().getResourceAsStream("/data/json/" + getFileName());
                if (is == null) {
                    is = AbstractJson.class.getResourceAsStream("/data/json/" + getFileName());
                }
                String data = toString(is);
                // 解析字符串
                if ("list".equals(type)) {
                    datas = JsonUtil.toMapList(data);
                    CACHE.put(fileName, datas);
                } else if ("map".equals(type)) {
                    datas = JsonUtil.toMap(data);
                    CACHE.put(fileName, datas);
                }
                if (is != null) {
                    is.close();
                }
            }
            return datas;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public abstract String getFileName() throws Exception;

    public static String toString(InputStream is) {
        String jsonStr = "";
        try {
            Reader reader = new InputStreamReader(is, "UTF-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
